import os

import settings
import logging


def get_logger(name):
    log = logging.getLogger(settings.app_name + '.' + name)
    log.setLevel(getattr(logging, settings.log_level))
    handler = logging.StreamHandler()
    handler.setFormatter(logging.Formatter(settings.log_format))
    log.addHandler(handler)
    log.info('log %s initialized' % name)
    return log


class Helpers():
    def __init__(self, handler):
        self.handler = handler

    def get_login_button(self):
        current_user = self.handler.get_current_user()
        if current_user:
            return '<a href="/logout">Вийти</a> (%s)' % current_user['name']
        else:
            return '<a href="/login">Увійти</a>'
            
            
def get_db(_instances_list=[]):
    if _instances_list:
        return _instances_list[0]
    from pymongo import Connection
    connection = Connection(settings.mongo.host, settings.mongo.port)
    db = connection[settings.mongo.db_name]
    _instances_list.append(db)
    return db


def run_mongod():
    os.system('mongod --dbpath {db_path} --port {port} &'.format(
        **settings.mongo.__dict__
    ))
